<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<!--
/**
 * @module Polymer Elements
 */
-->
<polymer-element name="g-selection" attributes="multi">
  <template>
    <style>
      @host {
        * {
          display: none !important;
        }
      }
    </style>
  </template>
  <script>
    Polymer('g-selection', {
      multi: false,
      ready: function() {
        this.clear();
      },
      clear: function() {
        this.selection = [];
      },
      getSelection: function() {
        return this.multi ? this.selection : this.selection[0];
      },
      isSelected: function(inItem) {
        return this.selection.indexOf(inItem) >= 0;
      },
      setItemSelected: function(inItem, inIsSelected) {
        if (inItem) {
          if (inIsSelected) {
            this.selection.push(inItem);
          } else {
            var i = this.selection.indexOf(inItem);
            if (i >= 0) {
              this.selection.splice(i, 1);
            }
          }
          // TODO(sjmiles): consider replacing with summary
          // notifications (asynchronous job)
          this.asyncFire("select", {isSelected: inIsSelected, item: inItem});
        }
      },
      select: function(inItem) {
        if (this.multi) {
          this.toggle(inItem);
        } else if (this.getSelection() !== inItem) {
          this.setItemSelected(this.getSelection(), false);
          this.setItemSelected(inItem, true);
        }
      },
      toggle: function(inItem) {
        this.setItemSelected(inItem, !this.isSelected(inItem));
      }
    });
  </script>
</polymer-element>
